package didi.hcp.questionrobot.controller;

import didi.hcp.questionrobot.bo.SopBO;
import didi.hcp.questionrobot.common.*;
import didi.hcp.questionrobot.entity.Sop;
import didi.hcp.questionrobot.group.AddGroup;
import didi.hcp.questionrobot.group.UpdateGroup;
import didi.hcp.questionrobot.service.ISopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * @author huchengpeng
 * @date 2021-12-11 16:37:35
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/sop/")
public class SopController extends BaseController {
    @Autowired
    private ISopService sopService;

    @PostMapping("getSop")
    public Answer getSop(@RequestBody SopRequest request){
        final Answer answer = new Answer();
        final List<Sop> sopList = this.sopService.getAllSop();
        sopList.parallelStream().forEach((sop)->{
            Arrays.stream(sop.getTriggerWord().split(",")).parallel().forEach(word->{
                if (request.getText().contains(word)) {
                    // 包括触发词
                    answer.appendMsg(Message.builder().text(sop.getContent()).color("#000").build());
                }
            });
        });
        if(answer.getData().isEmpty()){
            answer.appendMsg(Message.builder().text("很抱歉，没找到对应SOP。\n找值班同学吧~").build());
        }
        return answer;
    }

    @GetMapping("list")
    public CommonResponse list(QueryRequest request, SopBO sopBO){
        Map<String, Object> dataTable = getDataTable(this.sopService.findSops(request, sopBO));
        return CommonResponse.SUCCESS().data(dataTable);
    }

    @PostMapping("addSop")
    public CommonResponse addSop(@Validated(AddGroup.class) SopBO sopBO){
        sopService.addSop(sopBO);
        return sopService.addSop(sopBO)?CommonResponse.SUCCESS():CommonResponse.FAIL();
    }

    @PutMapping("updateSop")
    public CommonResponse updateSop(@Validated(UpdateGroup.class) SopBO sopBO){
        return sopService.updateSop(sopBO)?CommonResponse.SUCCESS():CommonResponse.FAIL();
    }

    @DeleteMapping("deprecatedSop")
    public CommonResponse deprecatedSop(SopBO sopBO){
        return sopService.deprecatedOrStartSop(sopBO)?CommonResponse.SUCCESS():CommonResponse.FAIL();
    }

}
